// 定义一个名为 tree-spot 的新组件
//isLoadDevice:是否加载设备结点，默认不加载
//get_children_spots:此方法返回选中站点所有子站点
//isLoadPing：是否加载RePing类型的设备
Vue.component('tree-spot-device', {
    props:{
        isLoadDevice: {
            type:Boolean,
            default:false//默认不加载设备
        },
        isLoadPing: {
            type:Boolean,
            default:true//默认加载RePing类型设备
        },
        includeCurrentNode:{
            type:Boolean,
            default:false//默认选择子节点时，不包含当前节点
        }
    },
    template: '<div>\
            <div :style="boxStyle">\
                    <div :style="treeBoxStyle">\
                        <span v-show="isCollapsed">列表</span>\
                        <el-button size="mini" icon="el-icon-refresh" circle @click="refresh" v-show="isCollapsed"></el-button>\
                        <div style="width:20px;height:20px;background: url(/images/fold.png);float:right;" @click="collapse"></div>\
                    </div>\
                <el-input v-show="isCollapsed" type="text" style="margin-bottom:10px;" class="tree" size="medium" placeholder="请输入内容" v-model="filterText" clearable prefix-icon="el-icon-search"></el-input>\
                <div class="spotTree">\
                    <el-tree\
                        :data="treeData"\
                        :expand-on-click-node="true"\
                        :highlight-current="true"\
                        :filter-node-method="filterNode"\
                        :check-on-click-node="true"\
                        @node-click="nodeClick"\
                        :load="loadNode"\
                        lazy\
                        ref="tree"\
                        v-show="isCollapsed">\
                        <div slot-scope="{ node, data }">\
                            <div style="float:left;">\
                                <i v-if="data.isDevice" style="display:inline-block;height: 25px;width:25px;background:url(/images/device.png)" ></i>\
                                <i v-else style="display:inline-block;height: 25px;width:25px;background:url(/images/spot.png)"></i>\
                            </div>\
                            <div style="margin-left: 30px;margin-top:3px;">{{ data.name }}</div>\
                        </div>\
                    </el-tree>\
                </div>\
            </div>\
        </div>',
    data: function () {
        return{
            filterText:'',
            isCollapsed:true,
            treeBoxStyle:{
                borderBottom:'1px solid #D9D9D9',
                paddingBottom: '10px',
                marginBottom: '10px'
            },
            boxStyle:{
                maxWidth:'100%',
                minHeight:'600px',
                maxHeight:'600px',
                border:'1px solid #D9D9D9',
                padding:'10px',
                width:'',
                // overflowY: 'auto'
            },
            treeData: []
        }
    },
    mounted:function(){
        this.treeData=[];
    },
    methods: {
        loadNode:function(node, resolve){
            // console.log('node',node);
            if(node.data.isDevice)
                return resolve([]);
            this.loadTreeData(node,resolve);
        },
        collapse:function(){
            if(this.isCollapsed)
                this.boxStyle.width='20px';
            else
                this.boxStyle.width='95%';

            this.$emit('collapse',this.isCollapsed);
            this.isCollapsed=!this.isCollapsed;

        },
        filterNode:function(value, data) {
            if (!value) return true;
            return data.name.indexOf(value) !== -1;
        },
        nodeClick:function (data,node) {
            console.log(data);
            var _this=this;
            //查询所有子结点返回给父组件
            var param={
                parentId:data.id
            }
            spotService.getSpotByParentId('/getChildrenById',param,{
                success : function(ret) {
                    console.log('sss',ret);
                    if(_this.includeCurrentNode){
                        ret.push({
                            id:data.id,
                            name:data.name,
                            parentId:data.parentId,
                            createdTime:data.createdTime,
                            pageInfo:null,
                            remark:data.remark
                        });
                        _this.$emit('get_children_spots',ret);
                    }else{
                        _this.$emit('get_children_spots',ret);
                    }

                    _this.$emit('node_click', data);
                    _this.$emit('input',data);
                },
                fail : function(res) {
                    _this.showFailMsg(res.msg);
                }
            })
        },
        loadTreeData:function (node,resolve) {
            //从后台加载树开控件数据
            var _this=this;
            var param={
                parentSpotId:'',
                isLoadDevice:_this.isLoadDevice ? 1 : 0,
                isLoadPing:_this.isLoadPing ? 1 : 0
            }
            if(node.level >= 1){
                param.parentSpotId=node.data.id;
            }
            spotService.getTreeSpotById('/getSpotTree',param,{
                success : function(ret) {
                    // console.log('ret',ret);
                    if(ret==undefined || ret.length ==0){
                        return resolve([]);
                    }
                    return resolve(ret);
                },
                fail : function(res) {
                    // _this.deleteLoading = false;
                    // console.log('res',res);
                    _this.showFailMsg(res.msg);
                }
            })
        },
        refresh:function () {
            console.log('refresh');
            var _this=this;
            var param={
                parentSpotId:'',
                isLoadDevice:_this.isLoadDevice ? 1 : 0,
                isLoadPing:_this.isLoadPing ? 1 : 0
            }
            spotService.getTreeSpotById('/getSpotTree',param,{
                success : function(ret) {
                    _this.treeData = ret;
                },
                fail : function(res) {
                    _this.showFailMsg(res.msg);
                }
            })
        }
    },
    watch: {
        filterText:function(val) {
            this.$refs.tree.filter(val);
        }
    }
})

Vue.component('device-channel', {
    props:{
        device: {
            type:Object,
            default:{}
        },
        virtualId:{
            type:String,
            default:""
        }
    },
    template: '<div style="min-height: 600px;max-height: 600px;">\
                <el-input type="text" style="margin-bottom:10px;" class="tree" size="medium" placeholder="查询通道" v-model="filterText" clearable prefix-icon="el-icon-search"></el-input>\
                <el-table :data="tableVm.data" border max-height="580">\
                    <el-table-column prop="channelCode" label="CH" min-width="120"></el-table-column>\
                    <el-table-column prop="name" label="通道名称" min-width="120"></el-table-column>\
                    <el-table-column label="操作">\
                        <template scope="scope">\
                            <el-button size="mini" type="primary" icon="el-icon-edit" @click="chooseChannel(scope.$index,scope.row)">选择</el-button>\
                        </template>\
                    </el-table-column>\
                </el-table>\
                <div class="block">\
                    <el-pagination\
                        @size-change="handleSizeChange"\
                        @current-change="handleCurrentChange"\
                        :pager-count="3"\
                        :current-page.sync="tableVm.pageIndex"\
                        :page-size="tableVm.pageSize"\
                        layout="sizes, prev, pager, next, jumper"\
                        :total="tableVm.total">\
                    </el-pagination>\
                </div>\
        </div>',
    data: function () {
        return{
            filterText:'',
            boxStyle:{
                maxWidth:'100%',
                minHeight:'600px',
                border:'1px solid #D9D9D9',
                padding:'10px',
                width:''
            },
            tableData:[{
                channelCode:"001",
                name:"输入电压"
            },{
                channelCode:"002",
                name:"电压下限"
            }],
            deviceId:this.device.id,
            tableVm : {
                loading : false,
                data : [],
                total : 1,
                pageIndex : 1,
                pageSize : 11,
                tempData : []
            },
            currentSearch:{
                deviceId: '',
                virtualId:this.virtualId,
                searchStr:this.filterText,
                pageInfo:{
                    pageIndex:1,
                    pageSize:10
                }
            }
        }
    },
    mounted:function(){
        this.loadChannel();
    },
    methods: {
        loadChannel:function (deviceId) {
            var _this=this;
            // console.log('device is ',this.device);
            // var param={
            //     deviceId: (deviceId == undefined || deviceId=="") ? this.device.id : deviceId,
            //     virtualId:this.virtualId,
            //     searchStr:this.filterText,
            //     pageInfo:{
            //         pageIndex:1,
            //         pageSize:this.tableVm.pageSize
            //     }
            // }
            this.currentSearch.deviceId=(deviceId == undefined || deviceId=="") ? this.device.id : deviceId;
            this.currentSearch.pageInfo.pageSize=this.tableVm.pageSize;

            channelService.getPageChannelList("/getPageChannelList",this.currentSearch,{
                success:function (res) {
                    _this.tableVm.data=res.dataList;
                    _this.tableVm.total = res.total;
                    _this.tableVm.pageIndex = res.pageNum;
                },
                fail:function (ret) {
                    _this.showFailMsg(ret.msg);
                }
            })

        },
        chooseChannel:function (index, row) {
            // console.log('row',row);
            var data={
                deviceCode:this.device.code,
                channelCode:row.channelCode
            }
            // console.log('data',data);
            this.$emit('input',data);
            this.$emit('chooseChannel',data);
        },
        handleSizeChange:function (val) {
            this.tableVm.pageSize=val;
            this.loadChannel(this.device.id);
        },
        handleCurrentChange : function(val) {
            this.currentSearch.pageInfo.pageIndex = val;
            this.loadChannel(this.device.id);
        },
    },
    watch: {
        filterText:function(val) {
            this.loadChannel(this.device.id);
        }
    }
})

Vue.component('calculator', {
    props:{
        disabled:{
            type:Boolean,
            default:false
        },
        virtualId:{
            type:String,
            default:""
        },
        value:{
            type:String,
            default:""
        }
    },
    template:'<el-col class="center">\
                <el-row :gutter="20">\
                    <el-col :span="12">\
                        <el-row>\
                            <el-input ref="col" :value="myValue" :disabled="disabled" type="textarea" rows="4" auto-complete="off" max-length="65535" @input="handleInput"/>\
                        </el-row>\
                        <el-row v-if="!disabled">\
                            <form name="calculator">\
                                <input id="clear" :disabled="disabled" type="button" class="btn other" value="C" @click="clear">\
                                <input :disabled="disabled" type="button" class="btn channel" value="Channel" @click="getChannel">\
                                <input :disabled="disabled" type="button" class="btn operator" value="MAX" @click="pushNum($event);">\
                                <input :disabled="disabled" type="button" class="btn operator" value="MIN" @click="pushNum($event);">\
                                <br>\
                                <input :disabled="disabled" type="button" class="btn num" value="7" @click="pushNum($event)">\
                                <input :disabled="disabled" type="button" class="btn num" value="8" @click="pushNum($event);">\
                                <input :disabled="disabled" type="button" class="btn num" value="9" @click="pushNum($event);">\
                                <input :disabled="disabled" type="button" class="btn operator" value="+" @click="pushNum($event);">\
                                <input :disabled="disabled" type="button" class="btn operator" value="SUM" @click="pushNum($event);">\
                                <br>\
                                <input :disabled="disabled" type="button" class="btn num" value="4" @click="pushNum($event);">\
                                <input :disabled="disabled" type="button" class="btn num" value="5" @click="pushNum($event);">\
                                <input :disabled="disabled" type="button" class="btn num" value="6" @click="pushNum($event);">\
                                <input :disabled="disabled" type="button" class="btn operator" value="*" @click="pushNum($event);">\
                                <input :disabled="disabled" type="button" class="btn operator" value="AVG" @click="pushNum($event);">\
                                <br>\
                                <input :disabled="disabled" type="button" class="btn num" value="1" @click="pushNum($event);">\
                                <input :disabled="disabled" type="button" class="btn num" value="2" @click="pushNum($event);">\
                                <input :disabled="disabled" type="button" class="btn num" value="3" @click="pushNum($event);">\
                                <input :disabled="disabled" type="button" class="btn operator" value="-" @click="pushNum($event);">\
                                <input :disabled="disabled" type="button" class="btn operator" value="," @click="pushNum($event);">\
                                <br>\
                                <input :disabled="disabled" type="button" class="btn num" value="0" @click="pushNum($event);">\
                                <input :disabled="disabled" type="button" class="btn operator" value="." @click="pushNum($event);">\
                                <input :disabled="disabled" type="button" class="btn operator" value="/" @click="pushNum($event);">\
                                <input :disabled="disabled" type="button" class="btn operator" value="(" @click="pushNum($event);">\
                                <input :disabled="disabled" type="button" class="btn operator" value=")" @click="pushNum($event);">\
                            </form>\
                        </el-row>\
                        <el-row>\
                        <div> 注：\
                        <div>max函数：取最大值，每项用“,”号隔开，如：max(C(127.0.0.1:70_003),4,C(127.0.0.1:100_001))</div>\
                        <div>min函数：取最小值，每项用“,”号隔开，如：min(C(127.0.0.1:70_003),4,C(127.0.0.1:100_001))</div>\
                        <div>sum函数：求和，每项用“,”号隔开，如：sum(C(127.0.0.1:70_003),4,C(127.0.0.1:100_001))</div>\
                        <div>avg函数：求平均值，每项用“,”号隔开，如：avg(C(127.0.0.1:70_003),4,C(127.0.0.1:100_001))</div>\
                        </div>\
                        </el-row>\
                    </el-col>\
                    <el-col :span="12">\
                        <div >\
                            <el-row :gutter="10">\
                                <el-col :span="8">\
                                    <tree-spot-device v-model="device" @node_click="selectDevice" v-bind:is-load-device="true" v-bind:is-load-ping="false"></tree-spot-device>\
                                </el-col>\
                                <el-col :span="16" >\
                                    <device-channel :device="device" v-model="deviceChannelObj" @chooseChannel="selectchanged" v-bind:virtual-id="virtualId" ref="comChannel"></device-channel>\
                                </el-col>\
                            </el-row>\
                        </div>\
                    </el-col>\
                </el-row>\
             </div>',
    data:function () {
        return{
            myValue: this.value,
            deviceVisible: true,
            devices: [],
            values: [],
            device:{},
            deviceChannelObj:{},
            showChannel:false
        }
    },
    mounted:function(){
        // console.log('input value',this.value);
    },
    methods: {
        clear:function(){
            this.myValue = ''
            this.$refs.col.focus()
            // console.log('this.$emit(input)',this.myValue,this.virtualId);
            this.$emit('input', this.myValue)
        },
        selectDevice:function(device){
            // console.log('selectDevice',device);
            this.device=device;
            this.showChannel=true;
            if(this.$refs.comChannel!=undefined){
                this.$refs.comChannel.currentSearch.pageInfo.pageIndex=1;
                this.$refs.comChannel.loadChannel(device.id);
            }

        },
        pushNum:function(obj) {
            var value = obj.currentTarget.value
            value = (value.indexOf('SUM') > -1 ||
                value.indexOf('AVG') > -1 ||
                value.indexOf('MAX') > -1 ||
                value.indexOf('MIN') > -1) ? value + '(' : value
            if (!this.myValue) { this.myValue = '' }
            this.myValue = this.myValue + value
            this.$refs.col.focus(1)
        },
        getChannel:function() {
            // this.myValue = this.myValue + 'C('
            this.values = []
            // this.deviceVisible = true
        },
        handleInput:function(e) {
            // console.log(e)
            this.myValue = e
            // this.$emit('input', this.myValue)
        },
        selectchanged:function(channel) {
            // console.log('channel',channel);
            var codes = []
            codes.push('C(' + channel.deviceCode + '_' + channel.channelCode + ')');
            if (!this.myValue) { this.myValue = '' }
            if (codes.length > 0) {
                this.myValue = this.myValue + codes.join(',')
            }
            // this.deviceVisible = false;
            this.showChannel=false;
        }
    },
    watch: {
        value: function() {
            this.myValue = this.value
        },
        myValue: function() {
            // console.log('this.$emit(input)',this.myValue,this.virtualId);
            this.$emit('input', this.myValue)
        }
    },

});


